import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-09-03
 * Time: 15:08
 */
public class TCPEchoClient {
    private Socket socket = null;

    public TCPEchoClient(String serverIP, int ServerPort) throws IOException {
        socket = new Socket(serverIP, ServerPort);
    }

    public void start() {
        System.out.println("客户端启动");
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream);
            Scanner in = new Scanner(System.in);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                //1.从控制台读取
                System.out.println("->");
                String request = in.next();
                //2.把请求发送给服务器
                printWriter.println(request);
                printWriter.flush();
                //printWriter这样的类,自带缓冲区,写入数据不会立即触发IO,而是先放入缓冲区中,等缓冲区攒了一波之和,再统一性发送
                //使用flush可以主动刷新缓冲区
                //3.从服务器读取响应
                if (!scanner.hasNext()) {
                    break;
                }
                String response = scanner.next();
                //4.打印结果
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
